# TODO: fix ^M line endings

import sys
import os

structure = []
package_stack = []
mo_dir = '~/TMP_SCRIPT_OUTPUT'

def try_enter(line, where, stack = []):
#where = package, model, connector, function
    is_model = False if where == 'package' else True
    name = ''
    if is_model and line.find('partial') == 0:
        #print '==================================== PARTIAL ' + line + ' ', line.find(where)
        line = line [8:]
    if line.find(where) == 0:
        pi = line.find(where) # index of package keyword
        ni = line.find(' ', pi) + 1 # index of package name
        si = line.find(' ', ni) + 1

        name = line[ni : si - 1 if si > 0 else len(line) ]
        stack.append(name)

        structure.append('/'.join(package_stack) + ('/' + name + '.mo' if is_model else ''))
        #print 'Entered ' + where + ' ' + '    '.join(['' for i in stack]) +  '/'.join(stack)

    return [name, stack]

def try_exit(line, stack):
    if len(stack) == 0:
        return ''
    if line.find('end') == 0:
        ei = line.find('end')
        name = line[ei + 4 : line.find(';', ei)]
        if name == stack[-1]:
            out_of = stack.pop()
            #print 'Out of      ' + '    '.join(['' for i in stack]) + out_of
            #print '----------------------------\n'
            return out_of

    return '' 

def write_mo(class_name, content):
    pa_dir = mo_dir + '/'.join(package_stack)
    if not os.path.exists(pa_dir):
        os.makedirs(pa_dir)
    f = open(pa_dir + '/' + class_name + '.mo', 'w')
    f.write(content)
    f.close()

def main():
    mo_file = sys.argv[1]
    global mo_dir
    mo_dir = '/home/vf/yadisk/modelica/src/models/'
    if not os.path.exists(mo_dir):
        os.mkdir(mo_dir)

    global structure
    global package_stack

    if not os.path.exists(mo_file):
        #print "File not found: " + mo_file
        return

    with open(mo_file) as f:
        lines = f.readlines()

    class_stack = []
    model = ''
    in_model = False
    it = 0
    for full_line in lines:
        it += 1
        if in_model:
            #print 'in_model ' + class_name + ' : --- ' + line,
            model += full_line[line_trim_index:-2] + '\n'

        line = full_line.strip()
        [package_name, package_stack] = try_enter(line, 'package', package_stack)
        if package_name:
            continue

        for where in ['model', 'connector', 'function']:
            [class_name, class_stack] = try_enter(line, where)
            if class_name:
                break
        if class_name:
            model = 'within ' + '.'.join(package_stack) + ';\n\n'
            line_trim_index = len(full_line) - 2 - len(line)
            model += full_line[line_trim_index:-2] + '\n'
            in_model = True
            continue
        
        out_of = try_exit(line, class_stack)
        if not out_of == '':
            #print '====================== MODEL =================='
            #print model
            write_mo(out_of, model)
            model = ''
            in_model = False

        out_of = try_exit(line, package_stack)
        if not out_of == '':
            #print '===================== PACKAGE ================='
            package = 'within ' + '.'.join(package_stack) + ';\n\n' + \
                      'package ' + out_of + '\n' + \
                      'end ' + out_of + ';\n'
            #print package
            write_mo(out_of + '/package', package)

    #for s in structure:
        #print s
    #print len(structure)    
    #print 'Iterations =', it, 'lines =', len(lines)
    print 'Please make sure to add proper imports to the root package.'
main()


